#pragma once

#include <iostream>
#include <memory>
#include "Epoller.hpp"
#include "Socket.hpp"
#include "Connection.hpp"
#include "Common.hpp"
#include "Channel.hpp"

using namespace SocketModule;


class Listener : public Connection
{
public:
    Listener(int port = defaultport)
        :_port(port)
        ,_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildTcpSocketMethod(_port);
        //epoll边缘触发模式+非阻塞
        SetEvent(EPOLLIN | EPOLLET);
        SetNonBlock(_listensock->Fd());
    }

    int GetSockFd() override
    {
        return _listensock->Fd();
    }


    //监听套接字的accept
    void Recver() override
    {
        InetAddr client;
        while(1)
        {
            int clientfd = _listensock->Accept(&client);
            //错误判断直接在Accept处理
            if(clientfd > 0)
            {
                std::shared_ptr<Connection> conn = std::make_shared<Channel>(clientfd, client);
                conn->SetEvent(EPOLLIN | EPOLLET);
                if(_handler != nullptr)
                    conn->RegisterHandler(_handler);
                GetOwner()->AddConnection(conn);
            }
            else if(clientfd < 0)
            {
                LOG(LogLevel::DEBUG) << "no connection, exit listensockfd accept";
                break;
            }
        }
    }


    void Sender(){}
    void Excepter(){}
    ~Listener()
    {}
private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};